package com.dubito.gallery.ui.gallery

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.dubito.gallery.data.GalleryItem
import com.dubito.gallery.data.GalleryModel
import com.dubito.gallery.data.SettingsRepository
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.onEach
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.launch
import org.koin.core.component.KoinComponent
import org.koin.core.component.get

sealed interface GalleryUiState {
    object Loading : GalleryUiState
    data class Success(
        val galleryItems: List<GalleryItem>,
        val tapCountOpenSettings: Int,
        val multiGoBack: Int
    ) : GalleryUiState
}

class GalleryViewModel : ViewModel(), KoinComponent {
    private val model: GalleryModel = get()
    private val settingsRepository: SettingsRepository = get()
    private var ignoreFolderIds: Set<String>? = null

    private val appSettingsStream = settingsRepository.appSettingsFlow.onEach { appSettings ->
        ignoreFolderIds = appSettings.ignoreFolderIds
        viewModelScope.launch(Dispatchers.IO) {
            model.load(appSettings.ignoreFolderIds)
        }
    }

    val uiState: StateFlow<GalleryUiState> = combine(
        appSettingsStream,
        model.galleryItemsFlow
    ) { appSettings, items ->
        GalleryUiState.Success(
            galleryItems = items,
            tapCountOpenSettings = appSettings.tapCountToOpenSettings,
            multiGoBack = appSettings.multiGoBack
        )
    }.stateIn(
        scope = viewModelScope,
        started = SharingStarted.WhileSubscribed(5000),
        initialValue = GalleryUiState.Loading
    )

    fun loadGallery() {
        viewModelScope.launch(Dispatchers.IO) {
            val ids = ignoreFolderIds
            if (ids != null) {
                model.load(ids)
            }
        }
    }
}